const express = require("express");
const fs = require("fs");
const moment = require("moment");
const _ = require("underscore");

const index = require("./service/userService");
const addRoute = require("./controller/addRoute");
const mongooseDao = require("./service/mongooseDao");

const app = express();

//日期格式化语言设置
moment.locale("zh-cn");
var locals = {
	moment : moment,
	formatPattern : {
		DATE : "LL",
		DATETIME : "LLL"
	}
};
_.extendOwn(app.locals, locals);

//读取配置文件
fs.readFile("./config.json","utf-8",function(err, data){
	if(err) {
		console.log("读取配置文件出错!");
		console.error(err);
		return;
	}
	const config = JSON.parse(data.toString());

	//静态资源目录
	app.use(express.static(__dirname + config.resource));

	//视图目录, 默认views目录
	app.set("views", config.views || "views");

	//模板引擎, 默认ejs
	app.set("view engine", config.view_engine || "ejs");

	//加载视图路由
	addRoute(app);

	//连接数据库
	mongooseDao.connect(config);

	var port = config.port || 7001;
	//启动监听程序
	app.listen(port, 511, function(){
		console.log(`在${port}端口执行监听...`);
	});
});